package com.mobimagic.lockscreen.view;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;

import com.mobimagic.lockscreen.R;

public class FadeBitmapHelper {
    public int topfadeHeight = 0;
    private Bitmap bitmap;

    private Canvas bitmapCanvas;
    private Rect bitmapRect = new Rect();

    public FadeBitmapHelper(Resources res) {
        topfadeHeight = res.getDimensionPixelSize(R.dimen.top_fade_height);
    }

    public Canvas preDraw(int width, int height) {
        if (width <= 0) {
            bitmapCanvas = null;
            return null;
        }
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(width, topfadeHeight, Bitmap.Config.ARGB_8888);
            bitmapCanvas = new Canvas(bitmap);
            bitmapRect.right = width;
            bitmapRect.bottom = topfadeHeight;
        } else if (bitmap.getWidth() != width) {
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
            bitmap = Bitmap.createBitmap(width, topfadeHeight, Bitmap.Config.ARGB_8888);
            bitmapCanvas = new Canvas(bitmap);
            bitmapRect.right = width;
            bitmapRect.bottom = topfadeHeight;
        }
        bitmapCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        if (bitmapCanvas != null) {
            bitmapCanvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
            bitmapCanvas.save();
            bitmapCanvas.clipRect(bitmapRect);

            bitmapCanvas
                    .translate(0, -(height - LayoutData.getInstance().getTopFadeViewMarginBottom() - topfadeHeight));

        }
        return bitmapCanvas;
    }

    public Bitmap endDraw() {
        if (bitmapCanvas != null) {
            bitmapCanvas.restore();
            return bitmap;
        }
        return null;
    }

}